package com.loongnoy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.loongnoy.entity.User;
import com.loongnoy.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @RequestMapping
    public String login(Model model) {
        model.addAttribute("user", new User());
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam(value = "username") String username,
                          @RequestParam(value = "password") String password,
                          Model model,
                          HttpServletRequest request) {
        User user = userService.login(username, password);
        if (user == null) {
            model.addAttribute("error", "用户名或密码错误");
            model.addAttribute("user", new User());
            return "login";
        }
        // 将用户名和用户角色保存到Session中
        HttpSession session = request.getSession();
        session.setAttribute("username", username);
        session.setAttribute("role", user.getRole());
        if ("manager".equals(user.getRole())) {
            return "managerCenter";
        } else if ("vip".equals(user.getRole())) {
            return "vipCenter";
        }else {
            return "commonCenter";
        }
    }

    @GetMapping("/userList")
    public String userList(HttpSession session, Model model,  RedirectAttributes redirectAttributes,HttpServletRequest request) {
        String header = request.getHeader("Referer");
        String role = (String) session.getAttribute("role");
        if (!"manager".equals(role)) {
            redirectAttributes.addFlashAttribute("error", "您没有权限访问该页面");
            return header;
        }
        List<User> userList = userService.findAll();
        model.addAttribute("userList", userList);
        return "userList";
    }

}